package com.icongyou.enterprise.config.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.math.BigDecimal;
import java.util.Map;

public class JsonToMapTypeHandler extends BaseTypeHandler<Map<String, BigDecimal>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    Map<String, BigDecimal> parameter, JdbcType jdbcType) throws SQLException {
        // 将 Map 转换为 JSON 字符串后存储
        String json = JSON.toJSONString(parameter);
        ps.setString(i, json);
    }

    @Override
    public Map<String, BigDecimal> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return parseJsonToMap(json);
    }

    @Override
    public Map<String, BigDecimal> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return parseJsonToMap(json);
    }

    @Override
    public Map<String, BigDecimal> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return parseJsonToMap(json);
    }

    private Map<String, BigDecimal> parseJsonToMap(String json) {
        if (json == null || json.trim().isEmpty()) {
            return null;
        }
        try {
            return JSON.parseObject(json, new TypeReference<Map<String, BigDecimal>>() {});
        } catch (Exception e) {
            // 如果解析失败，返回空Map
            return null;
        }
    }
}